package com.pengliu.config.logs;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSON;

@Aspect
@Component
public class ControllerLogAspect {
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
    
    @Pointcut("execution(* com.pengliu.controller.*.*(..))")
    public void controllerLog() {}
 
    @Around(value = "controllerLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
    	logger.info("〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓(Controller)〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        HttpServletResponse response = attributes.getResponse();
        //1.记录执行时间
        long startTime = System.currentTimeMillis();
        //2.请求映射路径
        String requestURI = request.getRequestURI();
        //3.Controller方法名
        String classMethod = joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()";
        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
        
        logger.info("●调用Controller:{}",classMethod);
        logger.info("●请求路径:{}\t请求时间:{}",requestURI,sdf.format(new Date(startTime)));
        
        Object result = joinPoint.proceed(joinPoint.getArgs());
        
        long endTime = System.currentTimeMillis();
        long totalTime = endTime - startTime;
        //4.返回结果
        logger.info("●最终返回:{}\t耗时:{}毫秒",JSON.toJSONString(result),totalTime);
        return result;
    }
}
